package stpmproject.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import stpmproject.controller.viewobject.ProjectVO;
import stpmproject.controller.viewobject.TaskVO;
import stpmproject.controller.viewobject.TotalVO;
import stpmproject.error.BusinessException;
import stpmproject.error.EmBusinessError;
import stpmproject.response.CommonReturnType;
import stpmproject.service.*;
import stpmproject.service.model.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * encoding: utf-8
 *
 * @Author: kou dui
 * @Date: 2019/5/25 23:20
 * @software: IntelliJ IDEA
 * @file: TaskController
 * @description:
 */
@Controller("task")
@RequestMapping("/task")
@CrossOrigin(allowedHeaders = {"*"},allowCredentials = "true") //springboot前端请求的跨域问题
public class TaskController extends BaseController {
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private BugService bugService;

    @Autowired
    private TodoService todoService;

    @RequestMapping("/get")
    @ResponseBody
    public CommonReturnType getTask(@RequestParam(name = "id") Integer taskId) throws BusinessException {
        TaskModel taskModel=taskService.getTaskById(taskId);
        if(taskModel==null){
            throw new BusinessException(EmBusinessError.TASK_NOT_EXIST);
        }
        TaskVO taskVO=convertVOFromModel(taskModel);
        return CommonReturnType.create(taskVO);
    }

    //获取任务列表,开启分页功能
    @RequestMapping(value = "/list",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listTask(@RequestParam(name = "page") Integer page,
                                     @RequestParam(name = "limit") Integer limit,
                                     HttpSession session){
        //开启分页
        Page tmpPage=PageHelper.startPage(page,limit);
        List<TaskModel> taskModelList=taskService.listTask();
        List<TaskVO> taskVOList=taskModelList.stream().map(taskModel -> {
            TaskVO taskVO=this.convertVOFromModel(taskModel);
            return taskVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(taskVOList,tmpPage.getTotal());
    }

    //获取任务列表,开启分页功能
    @RequestMapping(value = "/mytask",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listMyTask(@RequestParam(name = "page") Integer page,
                                     @RequestParam(name = "limit") Integer limit,
                                     HttpSession session) throws BusinessException {
        UserModel userModel= (UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        //开启分页
        Page tmpPage=PageHelper.startPage(page,limit);
        List<TaskModel> taskModelList=taskService.getTaskByAssginedTo("%"+userModel.getUsername()+"%");
        List<TaskVO> taskVOList=taskModelList.stream().map(taskModel -> {
            TaskVO taskVO=this.convertVOFromModel(taskModel);
            return taskVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(taskVOList,tmpPage.getTotal());
    }
    //获取统计总数
    @RequestMapping(value = "/total",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType total(HttpSession session) throws BusinessException {
        UserModel userModel= (UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TotalVO totalVO=new TotalVO();
        List<TaskModel> taskModelList=taskService.listTask();
        List<BugModel> bugModelList=bugService.listBug();
        List<ProjectModel> projectModelList=projectService.listProject();
        List<TodoModel> todoModelList=todoService.getTodoByCreater(userModel.getUsername());
        totalVO.setTotalBug(bugModelList.size());
        totalVO.setTotalProject(projectModelList.size());
        totalVO.setTotalTask(taskModelList.size());
        totalVO.setTotalTodo(todoModelList.size());
        System.out.println("totalVO = " + totalVO.getTotalBug());
        return CommonReturnType.create(totalVO);
    }

    //获取任务列表,开启分页功能
    @RequestMapping(value = "/group",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType groupTask(@RequestParam(name = "page") Integer page,
                                     @RequestParam(name = "limit") Integer limit,
                                     HttpSession session) throws BusinessException {
        //开启分页
        UserModel userModel=(UserModel)session.getAttribute("LOGIN_USER");
        Page tmpPage=PageHelper.startPage(page,limit);
        List<TaskModel> taskModelList=null;
        List<TaskVO> taskVOList=null;
        if(userModel!=null) {
            taskModelList = taskService.groupByUserName(userModel.getUsername());
            taskVOList=taskModelList.stream().map(taskModel -> {
                TaskVO taskVO = this.convertVOFromModel(taskModel);
                taskVO.setTotalTask(taskModel.getNumOfProject());
                taskVO.setAssginedTo(userModel.getUsername());
                taskVO.setRealName(userModel.getRealname());
                return taskVO;
            }).collect(Collectors.toList());
        }
        return CommonReturnType.create(taskVOList,tmpPage.getTotal());
    }

    //获取任务列表,开启分页功能
    @RequestMapping(value = "/myproject",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listProject(@RequestParam(name = "page") Integer page,
                                     @RequestParam(name = "limit") Integer limit,
                                     HttpSession session){
        //开启分页
        Page tmpPage=PageHelper.startPage(page,limit);
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        List<ProjectModel> projectModelList=taskService.getTaskByAssgined(userModel.getUsername());
        List<ProjectVO> projectVOList=projectModelList.stream().map(projectModel -> {
            ProjectModel projectModel1=projectService.getProjectByCode(projectModel.getProjectCode());
            ProjectVO projectVO=new ProjectVO();
            projectVO.setProjectCode(projectModel1.getProjectCode());
            projectVO.setProjectName(projectModel1.getProjectName());
            projectVO.setProjectStatus(projectModel1.getProjectStatus());
            projectVO.setProjectEndDate(projectModel1.getProjectEndDate().toDate());
            return projectVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(projectVOList,tmpPage.getTotal());
    }

    private TaskVO convertVOFromModel(TaskModel taskModel){
        if(taskModel==null){
            return null;
        }
        TaskVO taskVO=new TaskVO();
        BeanUtils.copyProperties(taskModel,taskVO);
        taskVO.setTaskStartDate(taskModel.getTaskStartDate().toDate());
        taskVO.setTaskEndDate(taskModel.getTaskEndDate().toDate());
        return taskVO;
    }

    @RequestMapping(value = "/start",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType startTask(@RequestParam(name = "id") Integer taskId,
                                      @RequestParam(name = "taskStartDate") String taskStartDate,
                                      HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TaskModel taskModel=taskService.getTaskById(taskId);
        if(taskModel==null){
            throw new BusinessException(EmBusinessError.TASK_NOT_EXIST);
        }
        if(!taskModel.getTaskAssginedTo().contains(userModel.getUsername())){
            throw new BusinessException(EmBusinessError.START_FAIL);
        }
        taskModel.setTaskStartDate(new DateTime(taskStartDate.replace(" ","T")));
        taskModel.setTaskStatus("进行中");
        taskService.updateTask(taskModel);
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/finish",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType finishTask(@RequestParam(name = "id") Integer taskId,
                                      @RequestParam(name = "taskEndDate") String taskEndDate,
                                       HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TaskModel taskModel=taskService.getTaskById(taskId);
        if(taskModel==null){
            throw new BusinessException(EmBusinessError.TASK_NOT_EXIST);
        }
        if(!taskModel.getTaskAssginedTo().contains(userModel.getUsername())){
            throw new BusinessException(EmBusinessError.FINISH_FAIL);
        }
        taskModel.setTaskEndDate(new DateTime(taskEndDate.replace(" ","T")));
        taskModel.setTaskStatus("已完成");
        taskService.updateTask(taskModel);
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/delete",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType deleteTask(@RequestParam(name = "id") Integer taskId,
                                       HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TaskModel taskModel=taskService.getTaskById(taskId);
        if(taskModel==null){
            throw new BusinessException(EmBusinessError.TASK_NOT_EXIST);
        }
        if(!taskModel.getTaskAssginedTo().contains(userModel.getUsername())){
            throw new BusinessException(EmBusinessError.DELETE_FAIL_2);
        }
        taskService.deleteTaskById(taskId);
        return CommonReturnType.create(null);
    }

    //创建任务接口
    @RequestMapping(value = "/create",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType createTask(@RequestParam(name = "taskProject") String taskProjectCode,
                                       @RequestParam(name = "taskPriority") String taskPriority,
                                       @RequestParam(name = "assginedToSelect") String assginedToTeam,
                                       @RequestParam(name = "taskName") String taskName,
                                       @RequestParam(name = "taskStartDate") String taskStartDate,
                                       @RequestParam(name = "taskEndDate") String taskEndDate,
                                       @RequestParam(name = "taskDesc") String taskDesc,
                                       HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TaskModel model=taskService.getByProjectAndNameAndTeam(taskProjectCode,taskName,assginedToTeam);
        TaskModel taskModel=new TaskModel();
        taskModel.setTaskProjectCode(taskProjectCode);
        taskModel.setTaskName(taskName);
        taskModel.setTaskPriority(taskPriority);
        //获取团队成员
        TeamModel teamModel=teamService.getTeamByProjectAndName(taskProjectCode,assginedToTeam);
        String member=teamModel.getTeamDeveloper()+","+teamModel.getTeamTester();
        taskModel.setTaskAssginedTo(member);
        taskModel.setTaskStartDate(new DateTime(taskStartDate.replace(" ","T")));
        taskModel.setTaskEndDate(new DateTime(taskEndDate.replace(" ","T")));
        taskModel.setTaskDesc(taskDesc);
        taskModel.setTaskCreater(userModel.getUsername());
        taskModel.setTaskStatus("未开始");
        taskService.createTask(taskModel);
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/update",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType updateTask(@RequestParam(name = "taskProject_edit") String taskProject_edit,
                                       @RequestParam(name = "taskPriority_edit") String taskPriority_edit,
                                       @RequestParam(name = "id") Integer taskId,
                                       @RequestParam(name = "assginedToSelect_edit") String assginedToSelect_edit,
                                       @RequestParam(name = "taskName_edit") String taskName_edit,
                                       @RequestParam(name = "taskStartDate_edit") String taskStartDate_edit,
                                       @RequestParam(name = "taskEndDate_edit") String taskEndDate_edit,
                                       @RequestParam(name = "taskDesc_edit") String taskDesc_edit,
                                       HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TaskModel taskModel=new TaskModel();
        taskModel.setId(taskId);
        taskModel.setTaskProjectCode(taskProject_edit);
        taskModel.setTaskPriority(taskPriority_edit);
        TeamModel teamModel=teamService.getTeamByProjectAndName(taskProject_edit,assginedToSelect_edit);
        String member="";
        if(teamModel!=null){
            member=teamModel.getTeamDeveloper()+","+teamModel.getTeamTester();
        }else{
            member=assginedToSelect_edit;
        }
        taskModel.setTaskAssginedTo(member);
        taskModel.setTaskName(taskName_edit);
        taskModel.setTaskStartDate(new DateTime(taskStartDate_edit.replace(" ","T")));
        taskModel.setTaskEndDate(new DateTime(taskEndDate_edit.replace(" ","T")));
        taskModel.setTaskDesc(taskDesc_edit);
        taskService.updateTask(taskModel);

        return CommonReturnType.create(null);
    }
}
